﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SharpSoft.Net
{
    public class UdpCommander
    {
        public UdpCommander(int localPort)
        {
            udp = new UdpClient(localPort);
        }
        private UdpClient udp;
        private bool isListening = false;
        public void Start()
        {
            isListening = true;
            receive();
        }

        public void Close()
        {
            isListening = false;
            udp.Close();
        }

        private void receive()
        {
            udp.BeginReceive(iar =>
             {
                 IPEndPoint ip = new IPEndPoint(0, 0);
                 byte[] data = null;
                 try
                 {
                     data = udp.EndReceive(iar, ref ip);
                 }
                 catch (Exception ex)
                 {
                     this.Failed?.Invoke(this, new ExceptionEventArgs() { Exception = ex });
                 }
                 if (isListening)
                 {
                     receive();
                 }
                 if (data != null)
                 {
                     try
                     {
                         this.DataReceived?.Invoke(this, new DataReceivedEventArgs(ip, data));
                     }
                     catch (Exception)
                     {
                     }
                 }


             }, null);

        }
        /// <summary>
        /// 接收收据异常时触发
        /// </summary>
        public event EventHandler<ExceptionEventArgs> Failed;
        /// <summary>
        /// 收到数据时触发
        /// </summary>
        public event EventHandler<DataReceivedEventArgs> DataReceived;

    }

    public class ExceptionEventArgs : EventArgs
    {
        public Exception Exception { get; set; }
    }

    public class DataReceivedEventArgs : EventArgs
    {
        public DataReceivedEventArgs(IPEndPoint remote, byte[] data)
        {
            this.Remote = remote;
            this.Data = data;
        }
        public IPEndPoint Remote { get; set; }
        public byte[] Data { get; set; }
    }
}
